<?php

namespace backend\modules\qywx\controllers;

use common\business\QywxApiService;
use common\business\QywxDepartmentService;
use common\business\QywxHelper;
use common\business\QywxUserService;
use common\helpers\StringUtil;
use common\models\qywx\QywxDepartment;
use Yii;
use common\models\qywx\Department;
use common\models\qywx\DepartmentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * DepartmentController implements the CRUD actions for Department model.
 */
class DepartmentController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Department models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DepartmentSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Department model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Department model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
//        $model = new Department();
//
//        if ($model->load(Yii::$app->request->post()) && $model->save()) {
//            return $this->redirect(['view', 'id' => $model->department_id]);
//        } else {
//            return $this->render('create', [
//                'model' => $model,
//            ]);
//        }


        $model = new Department();

        if (!$model->load(Yii::$app->request->post())) {
            return $this->render('create', [
                'model' => $model,
            ]);
        }

        $result = (new QywxDepartmentService())->create($model);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success', Yii::t('app', $result->message));
            return $this->redirect(['view', 'id' => $model->department_id]);
        }

        Yii::$app->getSession()->setFlash('error', Yii::t('app', $result->message));
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Department model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if (!$model->load(Yii::$app->request->post())) {
            return $this->render('update', [
                'model' => $model,
            ]);
        }

        $result = (new QywxDepartmentService())->update($model);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success', Yii::t('app', $result->message));
            return $this->redirect(['view', 'id' => $model->department_id]);
        }

        Yii::$app->getSession()->setFlash('error', Yii::t('app', $result->message));
        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Department model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $result = (new QywxDepartmentService())->delete($model);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success', $result->message);
            return $this->redirect(['index']);
        }
        Yii::$app->getSession()->setFlash('error', $result->message);
        return $this->redirect(['view', 'id' => $model->department_id]);
    }

    /**
     * Finds the Department model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Department the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Department::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSync($id = null){

    }

    public function actionGetUserList($id){
//        $result = (new QywxApiService())->getUserListByOrgId($id);
        $result = (new QywxUserService())->getByDepartmentId($id);

        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success', Yii::t('app', $result->message));
        }
        else{
            Yii::$app->getSession()->setFlash('error', Yii::t('app', $result->message));
        }
        $department = Department::findOne([
            'department_id' => $id,
        ]);
        return $this->redirect(['qywx-user/index', 'QywxUserSearch[qywx_user_department]' => $department->department_qywx_id]);
    }

    public function actionJsonAll($q){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = Department::find()
            ->select('department_qywx_id as id, department_name as text')
            ->andFilterWhere(['like', 'department_name', $q])
            ->orderBy([
                'department_qywx_id' => SORT_ASC,
            ])
            ->limit(50)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }
}
